package network;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Mariam
 */
public class ThreadReceiveFile extends Thread {

    private ServerSocket socket;
    private ChatNI parent;
    private File file;

    public ThreadReceiveFile(ServerSocket socket, ChatNI parent, File file) {
        this.socket = socket;
        this.parent = parent;
        this.file = file;
    }

    @Override
    public void run() {
        Socket newSocket = null;
        InputStream inputFile = null;
        OutputStream outputFile = null;
        System.out.println("reception d'un fichier...");
        try {
            newSocket = socket.accept();
            inputFile = newSocket.getInputStream();
            outputFile = new FileOutputStream(file);
            byte[] bufReception = new byte[1024];
            int i;
            while ((i = inputFile.read(bufReception)) != -1) {
                outputFile.write(bufReception, 0, i);
               // System.err.println(i);
            }
            System.out.println("TERMINE !");
        } catch (IOException ex) {
            Logger.getLogger(ThreadReceiveFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                inputFile.close();
                outputFile.flush();
                outputFile.close();
                newSocket.close();
            } catch (IOException ex) {
                Logger.getLogger(ThreadReceiveFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}
